<?php
/**
 * @file $HeadURL: tag.php $
 * @author $Author: LiangJian (liangjian@haibao.com) $
 * @date $Date: 2014-11-11 下午12:30:13 $
 * @brief 
 */
namespace haibao\cms\business;
use haibao\frame\data\query\Condition;

use \haibao\cms\data\Tag as TagData;
use \haibao\cms\model\data\Tag as TagModelData;
use \haibao\cms\model\filter\Tag as TagModelFilter;
use \haibao\cms\business\Brand as BrandBusiness;

class Tag extends \haibao\cms\business\Base{
    
	public static function getRelationTagsByName($name){
		$data = new TagData();
		
		return $data->getRelationTagsByName($name);
	}
	
    public static function getSameLeveTagByParentId($parentId){
        $data = new TagData();
        
        return $data->getSameLeveTagByParentId($parentId);
    }
    
	/**
	 * 
	 * @param \haibao\cms\model\filter\Tag $model
	 */
	public static function getTagsByFilter($model){
		$data = new TagData();
		
		return $data->getAll($model);
	}
	
	public static function updateTagType($tagId,$status){
	    $data = new TagData();
	    $data->updateTagType($tagId,$status);
	}
	
	/**
	 * 获取所有标签摘要信息
	 * @return array(TagId=>array(TagName,ParentId))
	 */
	public static function getAllTagDict(){
		$data = new TagData();
		return $data->getAllTagDict();
	}
	
	public static function getAllTagKeywords(){
	    $data = new TagData();
	    return $data->getAllTagKeywords();
	}
	
	/**
	 * 根据标签id查询标签信息
	 * @param $detail 只显示基本信息
	 */
	public static function getTagById($tagId, $brief = true){
		$data = new TagData();
		return $data->getTagById($tagId, $brief);
	}
	
	public static function getTagsById($tagIds){
		if(empty($tagIds)){
			return array();
		}
		$data = new TagData();
		$tagIds = array_map('intval', $tagIds);
		return $data->getTagsById($tagIds);
	}
	
	/**
	 * 根据标签名查询标签信息
	 * @param string $tagName 标签名
	 * @param int $tagId 需要排除的标签id，可以为空
	 */
	public static function getTagByTagName($tagName, $tagId = null){
		$data = new TagData();
		return $data->getTagByTagName($tagName, $tagId);
	}
	/**
	 * 更新标签状态
	 */
	public static function updateTagStatus($tagId,$status){
		self::checkOperation(self::FUNC_CODE_TAG_EDIT);
		
		if(!$tagId){
			throw new BusinessException("标签ID不能为空");
		}
		if(!$status){
			throw new BusinessException('标签状态不能我空');
		}
		$data = new TagData();
		$data->updateTagStatus($tagId,$status);
		
		self::saveOperateHistory(self::FUNC_CODE_TAG_EDIT, array('id'=>$tagId,'status'=>$status));
	}
	
	/**
	 * @param string $tagName
	 * @return array(\cms\haibao\model\data\Tag)
	 */
	public static function getTagsByName($tagName,$isEnable = false,$parentId = -1){
		$data = new TagData();
		$tagModels = $data->getTagsByName($tagName,$isEnable,$parentId);

		return $tagModels;
	}
	
	public static function getTagIdByName($tagName){
		$data = new TagData();
		return $data->getTagIdByName($tagName);
	}
	
	public static function getChildTagTree($tagName){
		$data = new TagData();
		$tagInfo = self::getTagByTagName($tagName);
		if(!$tagInfo){
			return false;
		}else{
			return $data->getChildrenTreeByTagId($tagInfo->Id);
		}
	}
	public static function getChildrenTreeByTagId($tagId){
		$data = new TagData();
		$tagTree = $data->getChildrenTreeByTagId($tagId);
		return $tagTree;
	}
	
	/**
	 * 获取TagTree通过标签名
	 */
	public static function getTagTreeByTagName($tagName,$isHasNoStructTag=true){
		$data = new TagData();
		$tagInfo = self::getTagByTagName($tagName);
		if(!$tagInfo || (!$isHasNoStructTag && $tagInfo->TopId == \haibao\cms\model\data\Tag::STRUCTURE_TAG)){
			return false;
		}else{
			$childrenTree = $data->getChildrenTreeByTagId($tagInfo->Id);
			$parentsTagObjArr = $data->getParentsTagArr($tagInfo->Id);
			$parentsTagArr = array();
			$parentTagTree = array();
			if($parentsTagObjArr){
				foreach($parentsTagObjArr as $key=>$tag){
					$parentsTagArr[$tag->Id] = array(
							TagModelFilter::CONDITION_FIELD_NAME_ID => $tag->Id,
							TagModelFilter::CONDITION_FIELD_NAME_TOPIC_ID => $tag->TopicId,
							TagModelFilter::CONDITION_FIELD_NAME_TAG_NAME => $tag->TagName,
							TagModelFilter::CONDITION_FIELD_NAME_PARENT_ID => $tag->ParentId,
							TagModelFilter::CONDITION_FIELD_NAME_TOP_ID => $tag->TopId,
							TagModelFilter::CONDITION_FIELD_NAME_TAG_LEVEL => $tag->TagLevel,
							TagModelFilter::CONDITION_FIELD_NAME_URL => $tag->Url,
							TagModelFilter::CONDITION_FIELD_NAME_TAG_STATUS=>$tag->TagStatus
					);
				}
				unset($parentsTagArr[$tagInfo->Id]);
			}
			
			if($parentsTagArr){
				foreach($parentsTagArr as $key=>$tag){
					if($key == $tagInfo->ParentId){
						$parentsTagArr[$key]['children'] = $childrenTree;
						break;
					} 
				}
			}
			$parentsTree = $data->getParentsChannelTree($parentsTagArr);
			return $parentsTree;
		}
	}
	/**
	 * 顶级标签
	 */
	public static function getTopTag(){
		$data = new TagData();
		return $data->getTopTag();
	}
	
	//测试用 会删
	public static function getTagTreeTwo($topId = null){
	    if(!$topId){
	        throw new BusinessException('顶级标签id不能为空');
	    }
	    $data = new TagData();
	    return $data->getTagTreeTwo($topId);
	}
	
	/**
	 * 获取标签树结构数组
	 * @param int $topId 顶级标签id
	 */
	public static function getTagTree($topId = null){
		if(!$topId){
			throw new BusinessException('顶级标签id不能为空');
		}
		$data = new TagData();
		return $data->getTagTree($topId);
	}
	/**
	 * 获取频道结构的标签树
	 * @param int $topId
	 */
	public static function getLevelTagTree($topId = 5){
		$data = new TagData();
		if($topId != 5){
			return null;
		}
		return $data->getLevelTagTree();
	}

	
	/**
	 * @param \haibao\cms\model\data\Tag $model
	 */
	public static function addTag($model, $external = false){
		self::checkOperation(self::FUNC_CODE_TAG_ADD);
		
		if(!$model->TagName){
			throw new BusinessException('标签名不能为空');
		}
		if(!isset($model->TagType)){
			throw new BusinessException("标签类型不能为空");
		}
		
		$data = new TagData();
		if (self::getTagByTagName($model->TagName)){
			throw new BusinessException('标签“'.$model->TagName.'”已存在');
		}
		$model->TagStatus = TagModelData::STATUS_ENABLE;
		
		if( isset($model->ParentId) && intval($model->ParentId) > 0 ){
			$tagInfo = self::getTagById($model->ParentId);
			$model->TagLevel = $tagInfo->TagLevel + 1;
			$model->TopId = $tagInfo->TopId;
		}
		
		$model->Creator = $model->Suser = self::getCurrentUser()->Id;
		$model->CreateTime = $model->LastModified = time();
		$model->TopicId = (int)($data->getMaxTopicId() + 1);
		$model->SiteType = TagModelData::SITETYPE_FASHION;
		
		self::setAlias($model);
		self::setTagUrl($model);
		
		$ailas = $data->getExistTag(explode(',', $model->Alias));
		if ($ailas != null){
			throw new BusinessException('标签别名：' . $ailas . ' 重复');
        }
        if($model->Alias){
        	$model->Alias = ','.$model->Alias.',';
        }
		$data->addTag($model);
		
		if( isset($model->ParentId) && intval($model->ParentId) == \haibao\cms\model\data\Tag::TOP_PARENT_ID ){
			$data->updateTagTopId($model->Id);
		}
			
		// 品牌、明星、设计师需要同步到相应的表中
		if(!$external && ($model->TagType == TagModelData::TYPE_BRAND  || $model->TagType == TagModelData::TYPE_STAR || $model->TagType == TagModelData::TYPE_DESIGNER)){
		    self::insertOther($model);
		}
		
		self::saveOperateHistory(self::FUNC_CODE_TAG_ADD, $model->toArray(true,true));
		return $model->Id;
	}
	
	/**
	 * @param \haibao\cms\model\data\Tag $model
	 */
	public static function editTag($model){
		self::checkOperation(self::FUNC_CODE_TAG_EDIT);
		
		if(!$model->TagName){
			throw new BusinessException('标签名不能为空');
		}
		if(!isset($model->TagType)){
			throw new BusinessException("标签类型不能为空");
		}
		
		$data = new TagData();
		if (self::getTagByTagName($model->TagName, $model->Id)){
			throw new BusinessException('标签“'.$model->TagName.'”已存在');
		}
		
		$tagInfo = $data->getTagById($model->Id, false);
		$model->TopicId = $tagInfo->TopicId;
		$model->ParentId = $tagInfo->ParentId;
		$model->TopId = $tagInfo->TopId;
		$model->Suser = self::getCurrentUser()->Id;
		$model->LastModified = time();
		
		self::setAlias($model);
		self::setTagUrl($model);
		
		$ailas = $data->getExistTag(explode(',', $model->Alias), $model->Id);
		if ($ailas != null){
			throw new BusinessException('标签别名：' . $ailas . ' 重复');
		}
		if($model->Alias){
			$model->Alias = ','.$model->Alias.',';
		}

		$data->updateTagById($model);
		if($model->TagType != $tagInfo->TagType){
			self::deleteOther($model->Id,$tagInfo->TagType,$model->ParentId);
			// 品牌、明星、设计师需要同步到相应的表中
			if($model->TagType == TagModelData::TYPE_BRAND  || $model->TagType == TagModelData::TYPE_STAR || $model->TagType == TagModelData::TYPE_DESIGNER){
				self::insertOther($model);
			}
		}	
		self::saveOperateHistory(self::FUNC_CODE_TAG_EDIT, $model->toArray(true,true));
	}
	
	/**
	 * 删除标签及其相关内容
	 */
	public static function deleteTag($tagId){
		self::checkOperation(self::FUNC_CODE_TAG_DELETE);
		
		if(!$tagId){
			throw new BusinessException("标签ID不能为空");
		}
		if(self::isExitstChildTag($tagId)){
			throw new BusinessException('当前分类下有子分类不能删除');
		}
		$data = new TagData();
		$data->deleteTagById($tagId);
		
		self::saveOperateHistory(self::FUNC_CODE_TAG_DELETE, $tagId);
	}
	
	/**
	 * 编辑标签详细描述
	 * @param int $tagId 标签id
	 * @param string $tagDesc 描述信息
	 */
	public static function editTagDesc($tagId, $tagDesc){
		if(!$tagId){
			throw new BusinessException("标签ID不能为空");
		}
		$data = new TagData();
		$data->updateById($tagId, array(
				TagModelFilter::CONDITION_FIELD_NAME_DESC => $tagDesc
			));
	}
	
	/**
	 * 清除标签缓存
	 */
	public static function clearCache(){
	    $data = new TagData();
	    $data->clearCache();
	}
	
	/**
	 * 转移标签
	 * @param int $tagId  要转移的标签id
	 * @param int $parentId 转移到标签ID
	 */
	public static function moveTag($tagId,$parentId){
		if(!$tagId || !$parentId){
			throw new BusinessException("标签ID不能为空");
		}
		$data = new TagData();
		$tagInfo = $data->getTagById($tagId);
		$moveTagInfo = $data->getTagById($parentId);
		$tagModel = new TagModelData();
		if($tagInfo && $moveTagInfo){
			$level = $tagInfo->TagLevel;
			$moveLevel = $moveTagInfo->TagLevel + 1;
			$plus = $moveLevel  - $level;
			$levelOp = '';
			if($plus){
				$opertor = $plus ? "+":'-';
				$levelOp = $opertor.abs($plus);
			}
			$tagModel->Id = $tagInfo->Id;
			$tagModel->TagLevel = $moveLevel;
			$tagModel->ParentId = $moveTagInfo->Id;
			$tagModel->TopId = $moveTagInfo->TopId;
			$tagModel->Creator = self::getCurrentUser()->Id;
			$tagModel->LastModified = new \DateTime();
			$chilTagIds = array();
			if($data->isExitstChildTag($tagId)){
				$chilTagIds = $data->getChildIdsByTagId($tagId);
			}
			$data->moveTag($tagModel,$chilTagIds,$levelOp);
		}
		
	}	
	public static function editTagParentId($tagId, $parentId){
		if(!$tagId){
			throw new BusinessException("标签ID不能为空");
		}
		$data = new TagData();
		$data->updateById($tagId, array(
				TagModelFilter::CONDITION_FIELD_NAME_PARENT_ID => $parentId
		));
		$data->clearCache();
	}
	/**
	 * 根据多个标签id查询父级标签id的集合
	 * @param array $tagIds
	 */
	public static function getParentsTagByIds($tagIds){
		if(!$tagIds || !is_array($tagIds)){
			throw new BusinessException("标签ID传入错误");
		}
		$retParentsArr = array();
		$data = new TagData();
		foreach ($tagIds as $tagId){
			$retParentsArr[$tagId] = $data->getParentsTagArr($tagId);
		}
		return $retParentsArr;
	}
	
	public static function getTopicIdByTagId($arrId){
		$data = new \haibao\cms\data\Tag();
		return $data->getTopicIdByTagId($arrId);
	}
	
	public static function getTagIdByTopicId($arrTagId){
		$data = new \haibao\cms\data\Tag();
		return $data->getTagIdByTopicId($arrTagId);
	}

	/**
	 * @param \haibao\cms\model\data\Tag $model
	 */
	public static function setTagUrl($model){
		if($model->ParentId == TagModelData::TOP_PARENT_ID && empty($model->Url)){
			throw new BusinessException('添加顶级标签url不能为空');
		}
		if($model->ParentId == TagModelData::TOP_PARENT_ID && !preg_match('/\/.*\//isU', $model->Url)){
			throw new BusinessException('顶级标签url格式错误，格式：/fashion/');
		}
	
		$url = '';
		if ($model->TagType == \haibao\cms\model\data\Tag::TYPE_BRAND){
			$url = sprintf(TagModelData::TYPE_BRAND_URL, $model->TopicId);
		} elseif($model->TagType == \haibao\cms\model\data\Tag::TYPE_STAR) {
			$url = sprintf(TagModelData::TYPE_STAR_URL, $model->TopicId);
		} elseif($model->TagType == \haibao\cms\model\data\Tag::TYPE_DESIGNER) {
			$url = sprintf(TagModelData::TYPE_DESIGNER_URL, $model->TopicId);
		} elseif($model->TagType == \haibao\cms\model\data\Tag::TYPE_TV) {
			$url = sprintf(TagModelData::TYPE_TV_URL, $model->TopicId);
		} else{
			$data = new TagData();
			if($model->TopId){
				$topModel = $data->getTagById($model->TopId);
				$url = $topModel->Url;
				if($model->ParentId == \haibao\cms\model\data\Tag::TOP_PARENT_ID){	// 顶级标签
					preg_match('/\/.*\//isU', $topModel->Url, $ret);
					$url = '/'.trim(current($ret), '/').'/';
				}elseif($model->ParentId == \haibao\cms\model\data\Tag::STRUCTURE_TAG){	// 无结构标签
					$url = '';
				}else{		// 其他普通标签
					preg_match('/\/.*\//isU', $topModel->Url, $ret);
					$channel = current($ret);
					$url = $channel . trim($model->TagName, '/') . '/';
				}
			}
		}
		$model->Url = $url;
	}
	
	/**
	 * 根据标签id查看是否是明星
	 * @param int or array $nameArr
	 * @return array 返回是明星数组
	 */
	public static function getCelebrityByTagId($tagIdArr){
		if(!$tagIdArr){
			return false;
		}
		
		$data = new \haibao\cms\data\Tag();
		$tagArr = $data->getTagsById($tagIdArr);
		
		$result = array();
		if($tagArr){
			foreach ($tagArr as $key=>$tag){
				if(
						isset($tag[\haibao\cms\model\filter\Tag::CONDITION_FIELD_NAME_TAG_TYPE])
					&&	$tag[\haibao\cms\model\filter\Tag::CONDITION_FIELD_NAME_TAG_TYPE] == \haibao\cms\model\data\Tag::TYPE_STAR
				){
					array_push($result, $tag[\haibao\cms\model\filter\Tag::CONDITION_FIELD_NAME_TAG_NAME]);
				}
			}
		}
		return $result;
	}
	
	/**
	 * 选择明星、品牌、设计师的同时添加到相应的表中
	 * @param \haibao\cms\model\data\Tag $model
	 * @param Bool $isAdd
	 */
	private static function insertOther($model,$isAdd=true){
		switch ( $model->TagType ) {
			case TagModelData::TYPE_BRAND:	
				$brandModel = new \haibao\cms\model\data\Brand();
				$brandModel->TagId = $model->Id;
				$brandModel->NameCN = $model->TagName;
				$brandModel->NameEN = $model->TagName;
				$brandModel->CreateBy = self::getCurrentUser()->Id;
				$brandModel->TagType = intval($model->TagType);
				if(\haibao\cms\business\Brand::getBrandInfoByTagId($brandModel->TagId)){
					$brandModel->Status = \haibao\cms\model\data\Brand::STATUS_ENABLE;
					\haibao\cms\business\Brand::UpdateBrandByTagId($brandModel);
				}else{
					\haibao\cms\business\Brand::AddBrandForOther($brandModel);
				}
 				break;
			case TagModelData::TYPE_STAR:
				$celebrityModel = new \haibao\cms\model\data\Celebrity();
				$celebrityModel->TagId = $model->Id;
				$rule ='/([\x{4e00}-\x{9fa5}]){1}/u';
				if (preg_match($rule,$model->TagName)) {
					$celebrityModel->NameCn = $model->TagName;
					$celebrityModel->NameEn = '';
				}else{
					$celebrityModel->NameCn = '';
					$celebrityModel->NameEn = $model->TagName;
				}
				$celebrityModel->TagType = intval($model->TagType);
				$celebrityModel->Editor = self::getCurrentUser()->Id;
				if($isAdd){
					\haibao\cms\business\Celebrity::addCelebrityForOther($celebrityModel);
				}else{
					\haibao\cms\business\Celebrity::UpdateCelebrityByTagId($celebrityModel);
				}
				break;
			case TagModelData::TYPE_DESIGNER:
			    $disignerModel = new \haibao\cms\model\data\designer\Designer();
			    $disignerModel->TagId = $model->Id;
			    $disignerModel->TopicId = $model->TopicId;
			    $disignerModel->NameCN = $model->TagName;
			    $disignerModel->NameEN = $model->TagName;
			    $disignerModel->CreateBy = self::getCurrentUser()->Id;
			    $disignerModel->TagType = intval($model->TagType);
			    if(\haibao\cms\business\Designer::getDesignerInfoByTagId($disignerModel->TagId)){
			        $disignerModel->Status = \haibao\cms\model\data\Designer\Designer::STATUS_DISABLE;
			        \haibao\cms\business\Designer::UpdateDesignerByTagId($disignerModel);
			    }else{
			        \haibao\cms\business\Designer::addDesigner($disignerModel);
			    }
			    break;
		}

	}
	/**
	 * 修改tagType类型为普通，删除相应数据
	 * @param \haibao\cms\model\data\Tag $model
	 * @param Bool $isAdd
	 */
	private static function deleteOther($tagId,$tagType,$parentId){
		switch ( $tagType ) {
			case TagModelData::TYPE_BRAND:
				BrandBusiness::deleteBrandByTagId($tagId);
				break;
			case TagModelData::TYPE_STAR:
				\haibao\cms\business\Celebrity::deleteCelebrityByTagId($tagId);
				break;
			case TagModelData::TYPE_DESIGNER:
				if($parentId == \haibao\cms\model\data\Tag::DESINGER_TAG_ID){
					BrandBusiness::deletecDesignerSpaceByTagId($tagId);
				}
				break;
		}
	
	}
	/**
	 * @param \haibao\cms\model\data\Tag $model
	 */
	private static function setAlias($model){
		if (is_string($model->Alias)){
			$str = str_replace('，', ',', $model->Alias);
			$arrAlias = array_unique( explode(',', $str) );
			$model->Alias = implode(',', $arrAlias);
		}
	}
	
	/**
	 * 当前分类下是否已经存在子分类
	 */
	private static function isExitstChildTag($tagId){
		$data = new \haibao\cms\data\Tag();
		$count = $data->isExitstChildTag($tagId);
		return $count > 0 ? true : false;
	}
	/**
	 * 获取内容相关的所有标签
	 */
	public static function getTagsByRelationName($content,$isMatchNoStruct){
		$data = new \haibao\cms\data\Tag();
		return $data->getTagsByRelationName($content,$isMatchNoStruct);
	}

	public static function loopGetParentTag($tagArr){
		$parentTagArr = array();
		if($tagArr){
			$parentTags = self::getParentsTagByIds($tagArr);
			foreach($parentTags as $key=>$children){
				$parentTagArr[$key] = '#'.self::createTreeStr($children,$key).'#';
			}
		}
		return $parentTagArr;
	}

	private static function createTreeStr($childTags,$currentTag,$arr=array()){
		if(isset($childTags[$currentTag])){
			array_unshift($arr,$currentTag);
			if($childTags[$currentTag]->ParentId != 0){
				return self::createTreeStr($childTags,$childTags[$currentTag]->ParentId,$arr);
			}else{
				return $arr ? implode('#',$arr) : '#';
			}
		}else{
			return $arr ? implode('#',$arr) : '#';
		}
	}
}
